<?php

namespace Buu\Modules\AutoLdap\Apis;

use App\Http\Controllers\Controller;
use Doraemon\model\Ldap\LdapGroup;
use Doraemon\model\Ldap\LdapRelated;
use Doraemon\service\Ldap\Schedule;
use Doraemon\tools\Log;
use Doraemon\tools\Openldap;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Encore\Admin\Layout\Content;

class Handlecallback extends Controller
{
    const CREATE_USER_TYPE = "create_user";

    const UPDATE_USER_TYPE = "update_user";

    const DELETE_USER_TYPE = "delete_user";

    // 部门创建
    const CREATE_PARTY_TYPE = "create_party";
    // 删除部门
    const DELETE_PARTY_TYPE = "delete_party";

    const ENCODING_AES_KEY = "gg68ns5775nWmYt09JtMGB8K2iVJYFJ515t99OtyYSw";

    const TOKEN = "5XaQ8cG6x2pULd";

    const CORP_ID = "wwa94f5a23a690cc6f";

    // 验证权限信息
    public function HandleCallbackGet(Request $request)
    {
        include_once __DIR__."/Callback/WXBizMsgCrypt.php";
        $requestData = $request->all();

        $encodingAesKey = self::ENCODING_AES_KEY;
        $token = self::TOKEN;
        $corpId = self::CORP_ID;

        $sVerifyMsgSig = $requestData["msg_signature"];
        $sVerifyTimeStamp = $requestData["timestamp"];
        $sVerifyNonce =$requestData["nonce"];
        $sVerifyEchoStr = $requestData["echostr"];

        // 需要返回的明文
        $sEchoStr = "";
        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            return $sEchoStr;
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }

    public function HandleCallbackPost(Request $request)
    {
        include_once __DIR__."/Callback/WXBizMsgCrypt.php";

        $requestData = $request->all();
        $sReqData = file_get_contents("php://input");

        $encodingAesKey = self::ENCODING_AES_KEY;
        $token = self::TOKEN;
        $corpId = self::CORP_ID;

        $sReqMsgSig = $requestData["msg_signature"];
        $sReqTimeStamp = $requestData["timestamp"];
        $sReqNonce =$requestData["nonce"];

        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);

        $sMsg = "";
        $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
        file_put_contents("/tmp/test.txt", $sMsg);
        if ($errCode == 0) {
            $callbackData = $sMsg;
//            $callbackData = "<xml><ToUserName><![CDATA[wwa94f5a23a690cc6f]]></ToUserName><FromUserName><![CDATA[sys]]></FromUserName><CreateTime>1612319824</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_contact]]></Event><ChangeType><![CDATA[create_user]]></ChangeType><UserID><![CDATA[xuzhongjie1]]></UserID><Name><![CDATA[徐忠杰1]]></Name><Mobile><![CDATA[18210418482]]></Mobile><Gender>1</Gender><Email><![CDATA[xuzhongjie1@haohaozhu.com]]></Email><Avatar><![CDATA[https://rescdn.qqmail.com/node/wwmng/wwmng/style/images/independent/DefaultAvatar$73ba92b5.png]]></Avatar><Department><![CDATA[110]]></Department><Status>4</Status><IsLeader>0</IsLeader><IsLeaderInDept><![CDATA[0]]></IsLeaderInDept><MainDepartment>110</MainDepartment></xml>";
//            $callbackData  ="<xml><ToUserName><![CDATA[wwa94f5a23a690cc6f]]></ToUserName><FromUserName><![CDATA[sys]]></FromUserName><CreateTime>1612322152</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_contact]]></Event><ChangeType><![CDATA[delete_party]]></ChangeType><Id>145</Id></xml>";
//           print_r($callbackData);die;
            $provider = Openldap::getLdapProvider();
            $data = \EasyWeChat\Kernel\Support\XML::parse($callbackData);

            switch ($data["ChangeType"]) {
                case self::CREATE_USER_TYPE:
                    $this->addUser($provider, $data, "add");
                    break;
                case self::UPDATE_USER_TYPE:
                    $this->addUser($provider, $data, "update");
                    break;
                case self::DELETE_USER_TYPE:
                    $this->deleteUser($provider, $data);
                    break;
                case self::CREATE_PARTY_TYPE:
                    $this->addParty($provider, $data);
                    break;
                case self::DELETE_PARTY_TYPE:
                    $this->deleteParty($provider, $data);
                    break;
            }

            print_r($callbackData);die;
        } else {
            $log = array_merge($requestData, array(
                "error_code" => $errCode,
                "data" => $sReqData
            ));

            Log::info("回调处理信息失败", $log);
        }
    }

    // 添加用户
    public function addUser($provider, $data, $type)
    {
        if (strpos($data["UserID"], "@") !== false) {
            $uid = substr($data["UserID"], 0, strpos($data["UserID"], "@"));
        } else {
            $uid = strtolower($data["UserID"]);
        }

        $name =  "";
        if (isset($data["Name"]) && $data["Name"]) {
            $name =  $data["Name"];
        }

        $mainDepartment = "";
        if (isset($data["MainDepartment"]) && $data["MainDepartment"]) {
            $mainDepartment =  $data["MainDepartment"];
        }

        $departmentIds = array();
        if (isset($data["Department"]) && $data["Department"]) {
            $departmentIds = is_array($data["Department"]) && $data["Department"] ? $data["Department"] : explode(",", $data["Department"]);
        }

        $mail = "";
        if (isset($data["Email"])) {
            $mail = $data["Email"];
        }

        $cn = substr($mail, 0, strpos($mail, "@"));

        if ($type == "add") {
            Openldap::addUser($provider, $cn, $name, $uid, $mainDepartment, $departmentIds, $mail,  "add");

            # 账户添加的时候 开通vpn账号
            if ($mail) {
                Schedule::initUserOpenVpn($mail);
            }
        } else if ($type == "update") {
            Openldap::addUser($provider, $cn, $name, $uid, $mainDepartment, $departmentIds, $mail,  "update");
        }
    }

    // 删除用户
    public function deleteUser($provider, $data)
    {
        $cn = strtolower($data["UserID"]);
        $mail = Openldap::getMailByCn($provider, $cn);

        Openldap::deleteEntry($provider, $cn);

        # 账户删除的时候 关闭vpn账号
        if ($mail) {
            Schedule::disableUserOpenVpn($mail);
        }
    }

    // 创建部门
    public function addParty($provider, $data)
    {
        $cn = $data["Name"];
        $rs = Openldap::addGroup($provider, $cn);

        if ($rs) {
            $addData = array(
                "type" => Schedule::GROUP_TYPE_DEPARTMENT_INDEX,
                "name" => $cn,
                "i_status" => LdapGroup::STATUS_NORMAL,
                "department_id" => $data["Id"]
            );

            LdapGroup::addInfo($addData);
        }
    }

    // 删除部门
    public function deleteParty($provider, $data)
    {
        $departInfo = LdapGroup::get("*",
            array(
                "department_id" => $data["Id"],
                "i_status" => LdapGroup::STATUS_NORMAL
            )
        );

        if (is_array($departInfo) && $departInfo) {
            $cn = $departInfo["name"];
            // 删除ldap记录
            Openldap::deleteEntry($provider, $cn);

            // 删除表里记录
            $departInfo = LdapGroup::getDataByName($cn);
            if (is_array($departInfo) && $departInfo) {
                // 删除表里部门信息
                $saveData = array(
                    "i_status" => LdapGroup::STATUS_DELETE
                );
                LdapGroup::saveInfo($departInfo["id"], $saveData);

                // 删除关联信息
                $updateWhere = array(
                    "org_id" => $departInfo["id"]
                );
                $updateData = array(
                    "i_status" => LdapRelated::STATUS_DELETE
                );

                LdapRelated::update($updateData, $updateWhere);
            }
        }
    }
}